import { HttpContext } from '@adonisjs/core/http'

import { createShopValidator } from '#validators/shop'
import BaseController from '#common/base_controller'
import { deleteIdsValidator } from '#validators/common'
import Goods from '#models/goods'
import vine from '@vinejs/vine'
import { Dictionary } from '@adonisjs/lucid/types/querybuilder'

export default class GoodsController extends BaseController {
  async list(ctx: HttpContext) {
    const filterValidate = vine.compile(
      vine.object({
        categoryId: vine.number().optional(),
        keywords: vine.string().optional(),
      })
    )
    const { categoryId, keywords } = await ctx.request.validateUsing(filterValidate)

    const filterWere: Dictionary<any, string> = {}
    if (categoryId && categoryId > 0) {
      filterWere.fkCategoryId = categoryId
    }

    return this.generatePageData(ctx, Goods, (query) => {
      query = query.leftJoin('dicts', 'goods.fk_category_id', '=', 'dicts.id')
      query = query.leftJoin('dicts as supplier', 'goods.fk_supplier_id', '=', 'dicts.id')
      query = query
        .select('goods.*')
        .select('dicts.name as categoryName')
        .select('supplier.name as supplierName')
        .if(keywords, function (query2) {
          query2.whereILike('goods.name', `${keywords}%`).andWhere(filterWere)
        })
      return query
    })
  }

  async create({ request }: HttpContext) {
    const data = await request.validateUsing(createShopValidator)
    return Goods.create(data)
  }

  async detail({ request }: HttpContext) {
    const { id } = request.qs()
    return Goods.findOrFail(id)
  }

  async update({ request }: HttpContext) {
    const id = request.param('id')

    const data = request.body()

    return Goods.query().where('id', id).update(data)
  }

  async delete({ request }: HttpContext) {
    const ids = await deleteIdsValidator.validate(request.body())
    return Goods.query().whereIn('id', ids).delete()
  }
}
